package com.tiantian.web.controller.capital;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tiantian.bean.PageBean;
import com.tiantian.domain.Businesscapitalchangesdetails;
import com.tiantian.domain.BusinesscapitalchangesdetailsId;
import com.tiantian.domain.Businessrechargedetails;
import com.tiantian.domain.Businessusers;
import com.tiantian.domain.Buyercapitalchangesdetails;
import com.tiantian.domain.BuyercapitalchangesdetailsId;
import com.tiantian.domain.Buyerraisecashdetails;
import com.tiantian.domain.Buyersusers;
import com.tiantian.domain.Fundschangereason;
import com.tiantian.poi.PoiReportBuilder;
import com.tiantian.ret.Result;
import com.tiantian.service.BackstagelogService;
import com.tiantian.service.BusinessCapitalChangesDetailsService;
import com.tiantian.service.BusinessUsersService;
import com.tiantian.service.BusinessrechargedetailsService;
import com.tiantian.service.BuyerCapitalChangesDetailsService;
import com.tiantian.service.BuyerRaiseCashDetailsService;
import com.tiantian.service.BuyersUsersService;
import com.tiantian.service.CapitalService;
import com.tiantian.service.FundsChangeReasonlService;
import com.tiantian.service.PlatformCapitalChangesService;
import com.tiantian.service.vo.SectionVo;
import com.tiantian.util.CommonConstant;
import com.tiantian.util.PageUtil;
import com.tiantian.web.datatables.DataTableReturn;

@Controller
@RequestMapping("/capital")
public class CapitalController {

	@Resource
	private CapitalService capitalService;
	@Resource
	private BusinessrechargedetailsService rechargeService;
	@Resource
	private BuyerRaiseCashDetailsService raiseCaseService;
	@Resource
	private BusinessUsersService businessUsersService;
	@Resource
	private BuyersUsersService buyerUsersService;
	@Resource
	private BusinessCapitalChangesDetailsService businessDetailsService;
	@Resource
	private BuyerCapitalChangesDetailsService buyerDetailService;
	@Resource
	private PlatformCapitalChangesService platformService;
	@Resource
	private FundsChangeReasonlService fundsChangeReasonService;
	@Autowired
	private BackstagelogService backstagelogService;

	public static final Logger LOG = LoggerFactory.getLogger(CapitalController.class);

	/**
	 * 前往平台资金明细界面
	 * 
	 * @return
	 */
	@RequestMapping("/detailList")
	public String detailList() {
		return "capital/detailList";
	}

	/**
	 * 获取平台资金明细数据
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("/getDetailList")
	@ResponseBody
	public Object getDetailList(DetailVo vo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Map<String, Object>> data = capitalService.detailsList(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	/**
	 * 前往商家充值界面
	 * 
	 * @return
	 */
	@RequestMapping("/rechargeDetailList")
	public String rechargeDetailList() {
		return "capital/rechargeDetailList";
	}

	/**
	 * 获取前往商家充值界面
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("/getRechargeDetailList")
	@ResponseBody
	public Object getRechargeDetailList(RechargeDetailVo vo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Map<String, Object>> data = rechargeService.rechargeDetailsList(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	/**
	 * 修改商家充值信息
	 * 
	 * @return
	 */
	@RequestMapping("/updateRechargeDetails")
	@ResponseBody
	public Object updateRechargeDetails(char statusInfor, String businessUserID, String applicationRechargeTime) {
		Map<String, String> param = new HashMap<>();
		param.put("businessUserID", businessUserID);
		param.put("applicationRechargeTime", applicationRechargeTime);
		List<Businessrechargedetails> list = this.rechargeService.getRechargeDetails(param);
		for (Businessrechargedetails temp : list) {
			temp.setStatusInfor(statusInfor);
			temp.setCompletionTime(new Date());
			// 日志
			if ('2' == statusInfor) {
				backstagelogService.log("051", temp.getId().getBusinessUserId(), "充值金额：" + temp.getRechargeAmount(), true);
			} else {
				backstagelogService.log("051", temp.getId().getBusinessUserId(), "充值金额：" + temp.getRechargeAmount(), false);
			}
			if ('2' == statusInfor) {
				// 通过，修改商家金额
				Businessusers users = this.businessUsersService.get(temp.getId().getBusinessUserId());
				BigDecimal amount = users.getBasicAccount();
				BigDecimal changeAmount = temp.getRechargeAmount();
				amount = amount.add(changeAmount);
				users.setBasicAccount(amount);
				this.businessUsersService.save(users);

				Fundschangereason fundsChangeReason = new Fundschangereason();
				fundsChangeReason.setChangeReasonId("-2");
				fundsChangeReason.setUserType('2');
				fundsChangeReason.setAccountName("商家基本账户");
				fundsChangeReason.setChangeReason("商家充值");
				// this.fundsChangeReasonService.save(fundsChangeReason);
				// 商家资金变动明细
				String platNo = this.platformService.getChangeNo(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd"));
				Businesscapitalchangesdetails changeDetails = new Businesscapitalchangesdetails();
				BusinesscapitalchangesdetailsId changeId = new BusinesscapitalchangesdetailsId();
				changeId.setBusinessUserId(users.getBusinessUserId());
				changeId.setChangeDate(new Date());
				String buyerNo = this.buyerDetailService.getChangeNo(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd"));
				changeId.setChangeNo(Integer.parseInt(buyerNo) + 1);
				changeDetails.setChangeAccount('0');
				changeDetails.setChangeBalance(changeAmount);
				changeDetails.setPaymentsDirection('1');
				changeDetails.setId(changeId);
				// fundsChangeReason.getChangeReasonId()
				changeDetails.setChangeReasonId("1");
				changeDetails.setAssociateOrderFormId(null);
				changeDetails.setAssociateTaskId(null);
				changeDetails.setMoneyAmount(temp.getRechargeAmount());
				this.businessDetailsService.save(changeDetails);

				// 平台资金变动明细
				// Platformcapitalchanges platformChange=new
				// Platformcapitalchanges();
				// PlatformcapitalchangesId platformId=new
				// PlatformcapitalchangesId();
				// platformId.setChangeDate(new Date());
				//
				// platformId.setChangeNo(Integer.parseInt(platNo)+1);
				// platformChange.setId(platformId);
				// platformChange.setAssociateOrderFormId(null);
				// platformChange.setAssociateTaskId(null);
				// platformChange.setChangeBalance(users.getBasicAccount());
				// platformChange.setChangeReasonId(fundsChangeReason.getChangeReasonId());
				// platformChange.setMoneyAmount(temp.getRechargeAmount());
				// platformChange.setPaymentsDirection('1');
				// platformChange.setTaskTypeMark('0');
				// this.platformService.save(platformChange);
			}
		}
		try {
			this.rechargeService.save(list);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("修改商家充值信息", e);
			return new Result<Object>(false, "操作失败");
		}

		return new Result<Object>(true, "操作成功");
	}

	/**
	 * 前往买手体现界面
	 * 
	 * @return
	 */
	@RequestMapping("raiseCashList")
	public String raiseCashList() {
		return "capital/raiseCashList";
	}

	/**
	 * 获取买手提现数据
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("/getRaiseCashList")
	@ResponseBody
	public Object getRaiseCashList(RasieCashVo vo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Map<String, Object>> data = raiseCaseService.getRaiseCashList(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	/**
	 * 修改买手提现状态
	 * 
	 * @param statusInfor
	 * @param businessUserID
	 * @param applicationRechargeTime
	 * @return
	 */
	@RequestMapping("/updateRaiseCash")
	@ResponseBody
	public Object updateRaiseCash(char statusInfor, String buyersUserID, String raiseCashTime) {
		try {
			return capitalService.updateRaiseCash(statusInfor, buyersUserID, raiseCashTime);
		} catch (Exception e) {
			LOG.error("修改买手体现状态信息", e);
			return new Result<Object>(false, "操作失败");
		}
	}

	@RequestMapping(value = { "/reportDetail" })
	public ModelAndView reportDetail(DetailVo vo, HttpServletRequest request, HttpServletResponse response) {

		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		try {
			page.setPageSize(0);
			List<Map<String, Object>> datas = this.capitalService.detailsList(params, page);
			PoiReportBuilder builder = new PoiReportBuilder();
			builder.appendHeader("时间", "生财ID", "账户类型", "收/支", "变动金额", "变动原因", "关联订单ID", "关联任务ID", "账户余额");
			if (datas != null) {
				for (Map<String, Object> data : datas) {
					List<String> poiData = new ArrayList<>();
					poiData.add(DateFormatUtils.format((Timestamp) data.get("changedate"), CommonConstant.TIME_FORMAT_YMDHMS));
					poiData.add((String) data.get("userid"));

					if ("0".equals(data.get("changeaccount"))) {
						if ("0".equals(data.get("usertype"))) {
							poiData.add("商家基本账户");
						} else if ("1".equals(data.get("usertype"))) {
							poiData.add("买手基本账户");
						}
					} else if ("1".equals(data.get("changeaccount"))) {
						if ("0".equals(data.get("usertype"))) {
							poiData.add("商家冻结账户");
						} else if ("1".equals(data.get("usertype"))) {
							poiData.add("买手生财账户");
						}
					}
					poiData.add((data.get("paymentsdirection") + "") == "0" ? "收" : "支");
					poiData.add(data.get("moneyamount") == null ? "" : data.get("moneyamount") + "");
					poiData.add(data.get("changreason") == null ? "" : data.get("changreason") + "");
					poiData.add(data.get("associateorderformid") == null ? "" : data.get("associateorderformid") + "");
					poiData.add(data.get("associatetaskid") == null ? "" : data.get("associatetaskid") + "");
					poiData.add(data.get("changebalance") == null ? "" : data.get("changebalance") + "");
					builder.appendData(poiData.toArray(new String[poiData.size()]));
				}
			}

			response.reset();// 不加这一句的话会出现下载错误
			String fileName = "商家充值明细_" + System.currentTimeMillis() + ".xls";
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); // 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 定义输出类型
			builder.write(response.getOutputStream());
			return null;
		} catch (Exception e) {
			LOG.error("导出商家充值明细异常", e);
			request.setAttribute("message", e.getMessage());
			return new ModelAndView("error.jsp");
		}
	}

	@RequestMapping(value = { "/reportRaiseCash" })
	public ModelAndView reportRaiseCash(RasieCashVo vo, HttpServletRequest request, HttpServletResponse response) {

		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		try {
			page.setPageSize(0);
			List<Map<String, Object>> datas = this.raiseCaseService.getRaiseCashList(params, page);
			PoiReportBuilder builder = new PoiReportBuilder();
			builder.appendHeader("生财ID", "提现申请时间", "提现金额", "提现银行", "开户名", "开户城市", "开户行", "账号", "体现状态", "处理时间", "完成体现");
			if (datas != null) {
				for (Map<String, Object> data : datas) {
					List<String> poiData = new ArrayList<>();
					poiData.add((String) data.get("buyersuserid"));
					poiData.add(DateFormatUtils.format((Timestamp) data.get("raisecashtime"), CommonConstant.TIME_FORMAT_YMDHMS));
					poiData.add(data.get("moneyamount") == null ? "" : data.get("moneyamount") + "");
					poiData.add(data.get("bankname") == null ? "" : data.get("bankname") + "");
					poiData.add(data.get("cardholdername") == null ? "" : data.get("cardholdername") + "");
					poiData.add(data.get("areaname") == null ? "" : data.get("areaname") + "");
					poiData.add(data.get("accountbankname") == null ? "" : data.get("accountbankname") + "");
					poiData.add(data.get("bankcardaccount") == null ? "" : data.get("bankcardaccount") + "");

					poiData.add((data.get("statusinfor") + "") == "1" ? "待处理" : "已提现");
					if (data.get("completiontime") != null) {
						poiData.add(DateFormatUtils.format((Timestamp) data.get("completiontime"), CommonConstant.TIME_FORMAT_YMDHMS));
					} else {
						poiData.add("");
					}
					poiData.add("");
					builder.appendData(poiData.toArray(new String[poiData.size()]));
				}
			}

			response.reset();// 不加这一句的话会出现下载错误
			String fileName = "买手提现明细_" + System.currentTimeMillis() + ".xls";
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); // 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 定义输出类型
			builder.write(response.getOutputStream());
			return null;
		} catch (Exception e) {
			LOG.error("导出买手提现明细异常", e);
			request.setAttribute("message", e.getMessage());
			return new ModelAndView("error.jsp");
		}
	}

	@RequestMapping(value = { "/reportRechargeDetail" })
	public ModelAndView reportRechargeDetail(RechargeDetailVo vo, HttpServletRequest request, HttpServletResponse response) {

		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		try {
			page.setPageSize(0);
			List<Map<String, Object>> datas = this.rechargeService.rechargeDetailsList(params, page);
			PoiReportBuilder builder = new PoiReportBuilder();
			builder.appendHeader("生财ID", "充值申请时间", "充值金额", "转账银行", "转账人姓名", "充值状态", "处理时间", "通过", "驳回");
			if (datas != null) {
				for (Map<String, Object> data : datas) {
					List<String> poiData = new ArrayList<>();
					poiData.add((String) data.get("businessuserid"));
					if (data.get("applicationrechargetime") == null) {
						poiData.add("");
					} else {
						poiData.add(DateFormatUtils.format((Timestamp) data.get("applicationrechargetime"), CommonConstant.TIME_FORMAT_YMDHMS));
					}
					poiData.add(data.get("rechargeamount") == null ? "" : data.get("rechargeamount") + "");
					poiData.add(data.get("bankname") == null ? "" : data.get("bankname") + "");
					poiData.add(data.get("payername") == null ? "" : data.get("payername") + "");
					String statusinfo = "";
					if ("1".equals(data.get("statusinfor") + "")) {
						statusinfo = "待处理";
					} else if ("2".equals(data.get("statusinfor") + "")) {
						statusinfo = "已充值";
					} else if ("3".equals(data.get("statusinfor") + "")) {
						statusinfo = "已驳回";
					}
					poiData.add(statusinfo);
					if (data.get("completiontime") == null) {
						poiData.add("");
					} else {
						poiData.add(DateFormatUtils.format((Timestamp) data.get("completiontime"), CommonConstant.TIME_FORMAT_YMDHMS));
					}
					poiData.add("");
					poiData.add("");
					builder.appendData(poiData.toArray(new String[poiData.size()]));
				}
			}

			response.reset();// 不加这一句的话会出现下载错误
			String fileName = "商家充值明细_" + System.currentTimeMillis() + ".xls";
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); // 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 定义输出类型
			builder.write(response.getOutputStream());
			return null;
		} catch (Exception e) {
			LOG.error("导出商家充值明细异常", e);
			request.setAttribute("message", e.getMessage());
			return new ModelAndView("error.jsp");
		}
	}

	/**
	 * 到划款页面
	 * 
	 * @return
	 */
	@RequestMapping("/crossSection")
	public String toCrossSection() {
		return "capital/crossSection";
	}

	/**
	 * 
	 * @param userId
	 *            用户id
	 * @param userType
	 *            用户类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUserInfo")
	public Result<Object> getUserInfo(@RequestParam String userId, @RequestParam String userType) {
		return capitalService.get(userId, userType);
	}

	@ResponseBody
	@RequestMapping("/doCrossSection")
	public Result<Object> crossSection(SectionVo sectionVo) {
		return capitalService.crossSection(sectionVo);
	}

}
